import {
  Button,
  DatePicker,
  Form,
  Input,
  InputNumber,
  Card,
  Upload,
  message,
  Space,
  UploadFile,
} from "antd";
import { useState } from "react";
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";
import type { GetProp, UploadProps } from "antd";
import dayjs from "dayjs";
type FileType = Parameters<GetProp<UploadProps, "beforeUpload">>[0];
const getBase64 = (img: FileType, callback: (url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result as string));
  reader.readAsDataURL(img);
};

const beforeUpload = (file: FileType) => {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJpgOrPng) {
    message.error("You can only upload JPG/PNG file!");
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("Image must smaller than 2MB!");
  }
  return isJpgOrPng && isLt2M;
};

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 14 },
  },
};

export default function Setting() {
  // 表单数据
  const [form] = Form.useForm();
  // Form.useWatch 是 Ant Design Form 组件提供的一个钩子函数，其用途是监听表单中指定字段的值变化，并且在该字段的值改变时重新渲染组件。
  const username = Form.useWatch("username", form);
  console.log(username, "username");
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  // 上传头像前的处理函数
  const handleChange: UploadProps["onChange"] = (info) => {
    if (info.file.status === "uploading") {
      setLoading(true);
      return;
    }
    if (info.file.status === "done") {
      getBase64(info.file.originFileObj as FileType, (url) => {
        setLoading(false);
        setImageUrl(url);
        setFileList([info.file]); // 更新 fileList
      });
    }
  };
  // 上传头像按钮
  const uploadButton = (
    <button style={{ border: 0, background: "none" }} type="button">
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>上传头像</div>
    </button>
  );
  const onFinish = async () => {
    try {
      const values = await form.validateFields();
      values.avatar = fileList[0]; // 将文件数据添加到表单值中
      console.log('Success:', values);
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  };
  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  }

  const onFill = () => {
    form.setFieldsValue({ username: 'dirunru', age: 18, birthday: dayjs('2000-01-01'), signature: '这是一个签名' });
  };
  const onReset = () => {
    form.resetFields();
    setFileList([]); // 清空文件列表
    setImageUrl(undefined); // 清空图片 URL
  };
  return (
    <>
      <Card
        variant="borderless"
        style={{ width: "100%", height: "calc(100vh - 140px)" }}
      >
        <Form
          {...formItemLayout}
          form={form}
          variant={"underlined"}
          style={{ maxWidth: 600 }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          {/* 上传头像 */}
          <Form.Item
            label="头像"
            name="avatar"
            rules={[{ required: false, message: "请上传头像" }]}
          >
            <Upload
              name="avatar"
              listType="picture-circle"
              className="avatar-uploader"
              showUploadList={false}
              action="https://660d2bd96ddfa2943b33731c.mockapi.io/api/upload"
              beforeUpload={beforeUpload}
              onChange={handleChange}
              fileList={fileList} // 使用 fileList 管理文件列表
            >
              {imageUrl ? (
                <img src={imageUrl} alt="avatar" style={{ width: "100%" }} />
              ) : (
                uploadButton
              )}
            </Upload>
          </Form.Item>
          <Form.Item
            label="姓名"
            name="username"
            rules={[{ required: true, message: "请输入姓名" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="年龄"
            name="age"
            rules={[{ required: true, message: "请输入年龄" }]}
          >
            <InputNumber style={{ width: "100%" }} />
          </Form.Item>

          <Form.Item
            label="生日"
            name="birthday"
            rules={[{ required: true, message: "请选择生日" }]}
          >
            <DatePicker style={{ width: "100%" }} />
          </Form.Item>

          <Form.Item
            label="个性签名"
            name="signature"
            rules={[{ required: true, message: "请输入签名" }]}
          >
            <Input.TextArea />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 6, span: 14 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
              <Button htmlType="button" onClick={onReset}>
                重置
              </Button>
              <Button htmlType="button" onClick={onFill}>
                填充
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </>
  );
}
